﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;
using System.Net.Mail;
using System.Data;
using System.Configuration;
using System.IO;
using System.Data.SqlClient;
using System.Net.Mime;

namespace TotalSport
{
    public partial class CustomerMaster : System.Web.UI.Page
    {
        string strCon = ConfigurationManager.ConnectionStrings["TotalSport"].ConnectionString;
       public SqlConnection conn;
        protected void Page_Load(object sender, EventArgs e)
        {        

            Pop3Client pop3Client = new Pop3Client();
            Response.Write("Mails started==>" + DateTime.Now.ToLongTimeString());
            try
            {
                
             //   if (pop3Client.Connected) pop3Client.Disconnect();

                pop3Client.Connect("smtp.mail.yahoo.com",25, true);
                pop3Client.Authenticate("rahulm506@yahoo.com", "india101");
             //   pop3Client.Connect("pop.gmail.com", 995, true);
             //   pop3Client.Authenticate("totalsportsjd@gmail.com", "30091984");
                int count = pop3Client.GetMessageCount();
                int success = 0;
                int fail = 0;
                if (count > 20) { count = 20; }
                for (int i = count; i >= 1; i -= 1)
                {
                    string strFromEmailID = "";
                    string strBody = "";
                    string strSubject = "";
                    string strMobile = "";
                    string strName = "";
                    Message message = pop3Client.GetMessage(i);
                    if (message.Headers.Subject.ToLower().Contains("enquiry for you") == true && message.Headers.From.Address.Contains("daemon@googlemail.com") == false)
                    {

                        MessagePart plainTextPart = message.FindFirstPlainTextVersion();
                        if (plainTextPart != null)
                        {
                            // The message had a text/plain version - show that one
                            string strmessage = plainTextPart.GetBodyAsText();
                            string strCustName = "";
                            string strLocation = "";
                            int intstartindex = strmessage.IndexOf("Caller\r\nEmail:") + 14;
                            if (intstartindex == 13) { intstartindex = strmessage.IndexOf("Caller Email:") + 14; }
                            int intendindex = strmessage.IndexOf("Call Date &\r\nTime:");
                            if (intendindex == -1) { intendindex = strmessage.IndexOf("Call Date & Time:"); }
                            if (intendindex > 1 && intstartindex > 16)
                            {
                                strmessage = strmessage.Substring(intstartindex, intendindex - (intstartindex));
                                if (strmessage.Contains("mailto"))
                                {
                                    intstartindex = strmessage.IndexOf("mailto") + 7;
                                    intendindex = strmessage.IndexOf(">");
                                    strmessage = strmessage.Substring(intstartindex, intendindex - intstartindex);
                                }

                                string strname = plainTextPart.GetBodyAsText();
                                intstartindex = strname.IndexOf("Caller Name:") + 12;
                                intendindex = strname.IndexOf("Caller\r\nRequirement:");
                                if (intendindex == -1) { intendindex = strname.IndexOf("Caller Requirement:"); }
                                if (intendindex == -1) { intendindex = strname.IndexOf("Caller\r\nPhone:"); }
                                if (intendindex == -1) { intendindex = strname.IndexOf("Caller Phone:"); }
                                if (intendindex != -1 && intstartindex > 11)
                                {
                                    strname = strname.Substring(intstartindex, intendindex - (intstartindex));
                                }
                                else { strname = ""; }

                                strCustName = strname;
                                if (strname.Contains("from"))
                                {
                                    strCustName = strname.Substring(0, strname.IndexOf("from"));
                                    strLocation = strname.Substring(strname.IndexOf("from") + 5);
                                }

                                string strphone = plainTextPart.GetBodyAsText();
                                string strphone2 = "";
                                intstartindex = strphone.IndexOf("Caller\r\nPhone:") + 14;
                                if (intstartindex == 13) { intstartindex = strphone.IndexOf("Caller Phone:") + 16; }
                                intendindex = strphone.IndexOf("Caller\r\nEmail:");
                                if (intendindex == -1) { intendindex = strphone.IndexOf("Caller Email:"); }
                                if (intendindex != -1 && intstartindex > 16)
                                {
                                    strphone = strphone.Substring(intstartindex, intendindex - (intstartindex));
                                }
                                else { strphone = ""; }

                                if (strphone.Contains(","))
                                {
                                    string strphone1 = strphone.Substring(0, strphone.IndexOf(","));
                                    strphone2 = strphone.Substring(strphone.IndexOf(",") + 2);
                                    strphone = strphone1;
                                }
                                Response.Write("<br> " + message.Headers.Subject + " from==> " + strname + " emailid==>" + strmessage);
                                Response.Flush();

                                InsertCustomer(strmessage, "Inquiry from Justdial", "", strphone, strname, strLocation, strphone2);

                                MailMessage mail = new MailMessage();
                                mail.From = new MailAddress("totalsportsjd@gmail.com", "TOTAL SPORTS");

                                mail.Subject = "Enquiry with JustDial TOTALSPORTSINDIA.IN ";
                                String strRequire = plainTextPart.GetBodyAsText();
                                intstartindex = strRequire.IndexOf("Caller\r\nRequirement:");
                                if (intstartindex == -1) { intstartindex = strRequire.IndexOf("Caller Requirement:"); }
                                intendindex = strRequire.IndexOf("Caller\r\nPhone:");
                                if (intendindex != -1 && intstartindex != -1)
                                {
                                    strRequire = strRequire.Substring(intstartindex + 20, intendindex - (intstartindex + 20));
                                    mail.Subject = "Enquiry with JustDial for " + strRequire;
                                }
                                else { strRequire = ""; }

                                FileInfo objfile = new FileInfo(Server.MapPath("TS.html"));
                                StreamReader reader = new StreamReader(objfile.FullName);
                                mail.Body = reader.ReadToEnd();
                                if (strmessage.Length > 1)
                                {
                                    SmtpClient client = new SmtpClient();
                                    client.Credentials = new System.Net.NetworkCredential("totalsportsjd@gmail.com", "30091984");
                                    client.Port = 587;
                                    string p = HttpContext.Current.Request.UserHostAddress;
                                    client.Host = "smtp.gmail.com";
                                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                                    //AlternateView av1 = AlternateView.CreateAlternateViewFromString(content, null, MediaTypeNames.Text.Html);
                                    mail.Attachments.Add(new Attachment(Server.MapPath("TS.pdf")));
                                    //LinkedResource logo = new LinkedResource(HttpContext.Current.Server.MapPath("logo.png"));
                                    //logo.ContentId = "companylogo";
                                    //logo.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
                                    //av1.LinkedResources.Add(logo);
                                    mail.To.Add(strmessage);
                                    // mail.AlternateViews.Add(av1);
                                    // mail.CC.Add("info@totalsportsindia.in");
                                    mail.ReplyToList.Add(new MailAddress("info@totalsportsindia.in"));
                                    mail.IsBodyHtml = true;
                                    client.EnableSsl = true;
                                    client.Send(mail);
                                }
                            }
                            else
                            {
                                Response.Write("<br>" + message.Headers.Subject + " ===> NO EMAILID FOUND ");
                                Response.Flush();

                            }
                        }

                        //MessageBox.Show(message.MessagePart.GetBodyAsText());
                        // Create a TreeNode tree that mimics the Message hierarchy
                        // TreeNode node = new TreeNodeBuilder().VisitMessage(message);

                        // Set the Tag property to the messageNumber
                        // We can use this to find the Message again later
                        //node.Tag = i;

                        // Show the built node in our list of messages
                        //listMessages.Nodes.Add(node);
                    }
                    pop3Client.DeleteMessage(i);

                }
            }
            catch (Exception exp)
            {
                Response.Write("<br><br><br>ERROR found==>" + exp.ToString());
            }
            finally
            {
                if (pop3Client.Connected == true)
                {
                    pop3Client.Disconnect();
                }
            }
            Response.Write("<br><br>Mails ended==>" + DateTime.Now.ToLongTimeString());

        }

        public void InsertCustomer(string strFromEmailID, string strSubject, string strBody, string strMobile, string strName, string strLocation, string strMobile2)
        {
            try
            {                
                conn = new SqlConnection(strCon);
                SqlCommand cmd = new SqlCommand("TS_InsertCustomerRecordbyMail", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter[] arrParam = new SqlParameter[7];                
                arrParam[0] = new SqlParameter("@Email", SqlDbType.VarChar);
                arrParam[0].Value = strFromEmailID;
                arrParam[1] = new SqlParameter("@strSubject", SqlDbType.VarChar);
                arrParam[1].Value = strSubject;
                arrParam[2] = new SqlParameter("@strBody", SqlDbType.VarChar);
                arrParam[2].Value = strBody;
                arrParam[3] = new SqlParameter("@mobile", SqlDbType.VarChar);
                arrParam[3].Value = strMobile;
                arrParam[4] = new SqlParameter("@Name", SqlDbType.VarChar);
                arrParam[4].Value = strName;
                arrParam[5] = new SqlParameter("@location", SqlDbType.VarChar);
                arrParam[5].Value = strLocation;
                arrParam[6] = new SqlParameter("@mobile2", SqlDbType.VarChar);
                arrParam[6].Value = strMobile2;

                foreach (SqlParameter param in arrParam)
                {
                    cmd.Parameters.Add(param);
                }

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();         
               
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

                            

        }

    }
}